var indexTpl = require('../views/index.html')

import MovieController from './MovieController'
import CinemaController from './CinemaController'
import ProfileController from './ProfileController'

$("#app").html(indexTpl)

class IndexController {
    constructor() {
        this.render() // 渲染header, main, footer框架
        this.bindTabbarEvent()
        this.bindHashChange()


        this.components = {
            movie: MovieController,
            cinema: CinemaController,
            profile: ProfileController
        }
    }

    bindHashChange() {
        $(window).on('hashchange', () => {
            let hash = location.hash && location.hash.substr(1) || 'position'
            this.setTabActive(hash)
            this.renderMain(this.components[hash])
        })
        $(window).on('load', () => {
            let hash = location.hash && location.hash.substr(1) || 'position'
            location.hash = hash
            this.renderMain(this.components[hash])
            this.setTabActive(hash)
        })
    }

    renderMain(controller) {
        controller.render()
    }

    setTabActive(hash) {
        $(`footer li[data-hash=${hash}]`).addClass('active').siblings().removeClass('active')
    }

    bindTabbarEvent() {
        $("footer li").on('tap', function() {
            let dataHash = $(this).attr('data-hash')
            location.hash = dataHash
        })
    }

    render() {
        $("#app").html(indexTpl)
    }
}

export default new IndexController()